package com.hs.app.produce;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.hs.app.model.CdcBiblio;
import com.hs.app.service.IProduceService;
import com.hs.auth.model.HsAccount;
import com.hs.auth.model.HsUserinfo;
import com.hs.core.action.BaseAction;
import com.hs.core.db.DBMgr;
import com.hs.core.db.QueryPage;
import com.hs.core.utils.StringUtilTool;
@Controller   
public class ProduceController  extends BaseAction {
    /**
	 * 
	 */
 	private static final Logger logger = Logger.getLogger(ProduceController.class);
	private IProduceService produceService;
	@Autowired  
	public void setProduceService(IProduceService produceService) {
		this.produceService = produceService;
	}  
	
	 /**
	  * 进入数据加工
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/startproduce.do")   
     public ModelAndView startproduce(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String pid = request.getParameter("pid");
		 HsAccount acc = this.getCurrentuser(request);
		 String username = null;
		 if(null != acc){
			 HsUserinfo userinfo = acc.getUserinfo();
			 if(null != userinfo)
				 username = userinfo.getUsername();
		 }
		 CdcBiblio objectinfo = (CdcBiblio)this.produceService.findByID(CdcBiblio.class, new Long(pid));
		 String dbusername = objectinfo.getPuser();
		 if(null == objectinfo.getStatus() && dbusername == null){
			 objectinfo.setStatus(1l);
			 objectinfo.setPuser(username);
			 this.produceService.saveObject(objectinfo);
		 }
		 DBMgr dbutil = DBMgr.getDbUtilInst(request.getSession().getServletContext());
		 List datalist = dbutil.queryList("select PAPERTITLE,SAVEPATH from CDC_FILEINFO where id=(select max(id) from CDC_FILEINFO where PAPERID=?)", new Object[]{pid});
         String filePath = null;
		 if(datalist.size()>0){
			Map filedata = (Map)datalist.get(0);
			filePath = (String)filedata.get("SAVEPATH");
		 }
		 StringBuffer infobuffer = new StringBuffer();
		 infobuffer.append("<p><strong>【摘要】</strong>");
		 infobuffer.append(StringUtilTool.NULL2Blank(objectinfo.getAbstract_()));
		 infobuffer.append("</p>\n");
		 infobuffer.append("<p><strong>【关键词】</strong>");
		 infobuffer.append(StringUtilTool.NULL2Blank(objectinfo.getKeyword()));
		 infobuffer.append("</p>\n");
		 infobuffer.append("<p><strong>【主题词】</strong>");
		 infobuffer.append(StringUtilTool.NULL2Blank(objectinfo.getSubjectword()));
		 infobuffer.append("</p>\n");
		 infobuffer.append("<p><strong>【期刊】</strong>");
		 infobuffer.append(StringUtilTool.NULL2Blank(objectinfo.getPeriodicalname()));
		 infobuffer.append("</p>\n");
		 infobuffer.append("<p><strong>【作者】</strong>");
		 infobuffer.append(StringUtilTool.NULL2Blank(objectinfo.getAuthor()));
		 infobuffer.append("</p>\n");
		 infobuffer.append("<p><strong>【作者单位】</strong>");
		 infobuffer.append(StringUtilTool.NULL2Blank(objectinfo.getAuthorunit()));
		 infobuffer.append("</p>\n");
		 infobuffer.append("<p><strong>【年份】</strong>");
		 infobuffer.append(StringUtilTool.NULL2Blank(objectinfo.getYearstr()));
		 infobuffer.append("</p>\n");
		 infobuffer.append("<p><strong>【卷】</strong>");
		 infobuffer.append(StringUtilTool.NULL2Blank(objectinfo.getVolume()));
		 infobuffer.append("</p>\n");
		 infobuffer.append("<p><strong>【期】</strong>");
		 infobuffer.append(StringUtilTool.NULL2Blank(objectinfo.getPerriod()));
		 infobuffer.append("</p>\n");
		 modelMap.put("filePath", filePath);
		 modelMap.put("biblioinfo", infobuffer.toString());
		 modelMap.put("pid", pid);
		 modelMap.put("btype", objectinfo.getBtype()); // 文献类型
		 modelMap.put("ptype", objectinfo.getPtype()); // 药物主题
		 System.out.println("=================>>>>> " + objectinfo.getBtype());
		 return new ModelAndView("app/produce/paperProduce",modelMap);
	 }
	 /**
	  * 进入数据加工
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/viewPaperinfo.do")   
     public ModelAndView viewPaperinfo(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 return new ModelAndView("app/produce/paperInfo",modelMap);
	 }
	 
	 /**
	  * 完成提交
	 * @param request
	 * @param response
	 * @param modelMap
	 * @throws IOException
	 */
	@RequestMapping(value = "/produce/overproduce.do")
	 public void overproduce(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws IOException{
		 String pid = request.getParameter("pid");
		 DBMgr dbo = this.getDbo(request);
		 dbo.update("update cdc_biblio set status = 2 where id = ?", new Object[]{pid});
		 
		 PrintWriter out = response.getWriter();
	     out.print("success");
	     out.flush();
	     out.close();
	 }
	 
	 /**
	  * 数据加工列表
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/paperlist.do")   
     public ModelAndView paperlist(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 HsAccount acc = this.getCurrentuser(request);
		 String pname = "";
		 if(acc!= null){
			 HsUserinfo userinfo = acc.getUserinfo();
			 if(null != userinfo)
				 pname = userinfo.getUsername();
		 }
		 Map authmap = this.getUserRoleCodeByUserid(request, acc.getId());
		 boolean isauth = false;
		 if(authmap.get("SCHD_ROLE3")!= null ||authmap.get("SCHD_ROLE1")!= null || 1 == acc.getId().intValue())
			 isauth = true;
		 String orderName = request.getParameter("orderName");
		 String orderNum = request.getParameter("orderNum");
		 String username = request.getParameter("username");
		 String startdate = request.getParameter("startdate");
		 String enddate = request.getParameter("enddate");
		 String periodicalname = request.getParameter("periodicalname");
		 String title = request.getParameter("title");
		 String datatype = request.getParameter("datatype");
		 if(null == datatype)
			 datatype = "0";
		 StringBuffer orderByStr = new StringBuffer(" order by ");
		 if(StringUtils.isNotBlank(orderName)){
		    	if("1".equals(orderNum)){
		    		orderByStr.append(orderName).append(" asc");
		    	}
		    	if("2".equals(orderNum)){
		    		orderByStr.append(orderName).append(" desc");
		    	}
		    }else{
		    	orderByStr.append("title").append(" asc");
		    	orderName = "title";
		    	orderNum = "2";
		    }
		 request.setAttribute("orderName", orderName); 
		 request.setAttribute("orderNum", orderNum); 
		 request.setAttribute("startdate", startdate); 
		 request.setAttribute("enddate", enddate); 
		 request.setAttribute("periodicalname", periodicalname); 
 		 request.setAttribute("title", title==null?title:title.trim());
 		 request.setAttribute("username", username); 
		 Map conditionmap = new HashMap();
		 StringBuffer sqlbuffer = new StringBuffer();
		 StringBuffer chnsearchBuffer = new StringBuffer(" select * from CDC_BIBLIO  where 1=1   ");
		 
		 if(!isauth){
			 chnsearchBuffer.append(" and (puser='").append(username).append("' ");
			 chnsearchBuffer.append(" or status is null or status =1)");
		 }
 
		 StringBuffer conditionbuffer = new StringBuffer();
		 
		 if(StringUtils.isNotBlank(title)){
			String temp = title.trim();
			conditionbuffer.append(" and title like '%").append(temp).append("%' ");
			conditionmap.put("title", temp); 
		 }  
		 if(StringUtils.isNotBlank(username)){
				String temp = username.trim();
				conditionbuffer.append(" and puser like '%").append(username).append("%' ");
				conditionmap.put("username", username); 
			 }  
		 if(StringUtils.isNotBlank(startdate)){
			startdate = startdate.replaceAll("-", "");
			conditionbuffer.append(" and to_date(impdate,'yyyy-MM-dd')>=to_date('").append(startdate).append("','yyyy-MM-dd') ");
			conditionmap.put("startdate", startdate);
		 }
		 if(StringUtils.isNotBlank(enddate)){
			enddate = enddate.replaceAll("-", "");
			conditionbuffer.append(" and to_date(impdate,'yyyy-MM-dd')<=to_date('").append(enddate).append("','yyyy-MM-dd')");
			conditionmap.put("enddate", enddate);

		 }
		 if(StringUtils.isNotBlank(periodicalname)){ 
				conditionbuffer.append(" and periodicalname like '%").append(periodicalname).append("%'");
				conditionmap.put("periodicalname", periodicalname);
         } 
		 
			 sqlbuffer.append(chnsearchBuffer);
			 sqlbuffer.append(conditionbuffer);
			 
		 logger.debug("sql:" + sqlbuffer);
		 //sqlbuffer.append(orderByStr);
		 conditionmap.put("orderName", orderName==null?"":orderName); 
		 conditionmap.put("orderNum", orderNum==null?"":orderNum); 
		 
		 conditionmap.put("startdate", startdate==null?"":startdate); 
		 conditionmap.put("enddate", enddate==null?"":enddate); 
		 conditionmap.put("periodicalname", periodicalname==null?"":periodicalname); 
		 conditionmap.put("title", title==null?"":title.trim());
		 String sql = "select * from ("+sqlbuffer+") "+orderByStr;
	     QueryPage qp = new QueryPage(request,request.getContextPath()+"/produce/paperlist.do",sql,conditionmap); 
		 qp.query();  
		 String pagenum =  qp.getCurrentPageNo() + "";
		 String pagecount = qp.getPerPageCount() + "";
		 modelMap.put("pagenum", pagenum); 
		 modelMap.put("pagecount", pagecount);
		 modelMap.put("pagestr", qp.getPageStr());
		 modelMap.put("datalist", qp.getDataList());  
		 modelMap.put("datatype", datatype); 
		 System.out.println("pageStr:" + qp.getPageStr());
		 return new ModelAndView("app/produce/paperlist",modelMap);
	 } 
}
